﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DemoPersonalizeSearch
{
    public static class SimilarityMethod
    {
        
        public static double GetCosinSimilarity(this UserItem ui, WResultItem ri) {
            List<TagItem> list = ui.Tags.GroupBy(x => x.TagName.ToLower()).Select(y => new TagItem(y.Key, (int)y.Sum(z=>z.Weight))).ToList();
            List<TagItem> list2 = ri.Tags.GroupBy(x => x.TagName.ToLower()).Select(y => new TagItem(y.Key, (int)y.Sum(z => z.Weight))).ToList();

            list.AddRange(list2);
         
            var groups = list.GroupBy(x => x.TagName.ToLower()).Select(y => new {Tag = y.Key,Weights = y}).Where(z=>z.Weights.Count()>1);
            double tuso = 0;
            foreach (var item in groups)
            {
                double m = 1;
                foreach (var i in item.Weights)
                {
                    m *= i.Weight;
                    //Console.Write("i");
                }
                //Console.Write(" ");
                tuso += m;
            }
            double sum1 = 0;
            foreach (var item in ui.Tags)
            {
                sum1 += item.Weight * item.Weight;
            }
            sum1 = Math.Sqrt(sum1);
            double sum2 = 0;
            foreach (var item in ri.Tags)
            {
                sum2 += item.Weight * item.Weight;
            }
            sum2 = Math.Sqrt(sum2);
            
            return (tuso/(sum1*sum2));
        }
    }
    
}
